/**
 * 
 */
package com.brewdroid.db.dao;

import java.util.ArrayList;

import android.content.ContentValues;
import android.database.Cursor;

import com.brewdroid.db.DatabaseHelper;
import com.brewdroid.model.Adjunct;
import com.brewdroid.model.Hop;
import com.brewdroid.model.Ingredient;
import com.brewdroid.model.IngredientStep;
import com.brewdroid.model.Malt;
import com.brewdroid.model.Yeast;

/**
 * @author meeusen
 *
 */
public class IngredientStepDAO {

	private static final String TABLE="ingredientStep";
	private static final String NULL_COL="unitType";
	private static final String INGREIDENTSTEP_SELECT_ALL="select * from ingredientStep";
	private static final String INGREDIENTSTEP_SELECT_ID="select i._id from ingredientStep i where i.adjunct_id=? and i.hop_id=? and i.yeast_id=? and i.malt_id=? and i.unitType=? and i.quantity=?";
	private static final String INGREDIENTSTEP_SELECT_INGREDIENTS_FOR_RECIPE="select * from ingredientStep i where i.recipe_id =?";
	private static final String INGREDIENTSTEP_UPDATE_WHERE_CLAUSE="_id=?";
	//private static final String INGREDIENTSTEP_UPDATE_ASSIGN_ING ="where _id = ?";
	
	
	public static void addIngredientStep(DatabaseHelper db, IngredientStep step)
	{
		if(getId(db, step)==0)	//only add stuff thats not there already
		{
			ContentValues cv= new ContentValues();
			cv.put("quantity", step.getQuantity());
			cv.put("unitType", step.getUnitType());
			//default all the foriegn keys because of how INGREDIENTSTEP_SELECT_ID is going to query into it.
			cv.put("hop_id", "0");
			cv.put("malt_id", "0");
			cv.put("yeast_id", "0");
			cv.put("adjunct_id", "0");	
			//now re-set the one real id
			if(step.getIngredient() instanceof Hop)
				cv.put("hop_id",Integer.toString(HopDAO.getId(db,(Hop)step.getIngredient())));
			else if(step.getIngredient() instanceof Malt)
				cv.put("malt_id", Integer.toString(MaltDAO.getId(db, (Malt)step.getIngredient())));
			else if(step.getIngredient() instanceof Yeast)
				cv.put("yeast_id", Integer.toString(YeastDAO.getId(db, (Yeast)step.getIngredient())));
			else if(step.getIngredient() instanceof Adjunct)
				cv.put("adjunct_id", Integer.toString(AdjunctDAO.getId(db, (Adjunct)step.getIngredient())));
			
			db.getWritableDatabase().insert(TABLE,NULL_COL,cv);
		}
	}
	
	public static void addToRecipe(DatabaseHelper db, IngredientStep is, int recipe_id)
	{
		int ingredientStepId=getId(db, is);
		//if the ingredientStep doesnt exist (because it wasn't already saved to db) save if and re-query it.
		if(ingredientStepId==0)
		{
			addIngredientStep(db, is);
			ingredientStepId=getId(db, is);
		}
		
		ContentValues cv = new ContentValues();
		cv.put("recipe_id", recipe_id);
		
		db.getWritableDatabase().update(TABLE, cv, INGREDIENTSTEP_UPDATE_WHERE_CLAUSE, new String[]{Integer.toString(ingredientStepId)});
	}
	
	
	public static int getId(DatabaseHelper db, IngredientStep is)
	{
		String hopId, maltId, yeastId, adjunctId;
		Ingredient in = is.getIngredient();
		
		if(in instanceof Hop)
			hopId=Integer.toString(HopDAO.getId(db, (Hop)in));
		else
			hopId="0";
		
		if(in instanceof Malt)
			maltId=Integer.toString(MaltDAO.getId(db, (Malt)in));
		else
			maltId="0";
		
		if(in instanceof Yeast)
			yeastId=Integer.toString(YeastDAO.getId(db, (Yeast)in));
		else 
			yeastId="0";
		
		if(in instanceof Adjunct)
			adjunctId=Integer.toString(AdjunctDAO.getId(db, (Adjunct)in));
		else
			adjunctId="0";
				
		Cursor c = db.getReadableDatabase().rawQuery(INGREDIENTSTEP_SELECT_ID, new String[]{ 	adjunctId,
																								hopId,
																								yeastId,
																								maltId,
																								is.getUnitType().toString(),
																								Double.toString(is.getQuantity())
				
		});
		 
		return c.moveToFirst()?c.getInt(0):0;
	}
	
	public static ArrayList<IngredientStep> getIngredientStepsForRecipe(DatabaseHelper db, int recipe_id)
	{
		ArrayList<IngredientStep> ins = new ArrayList<IngredientStep>();
		Cursor c = db.getReadableDatabase().rawQuery(INGREDIENTSTEP_SELECT_INGREDIENTS_FOR_RECIPE, new String[]{Integer.toString(recipe_id)});
		
		if(c.moveToFirst())
		{
			int hopId,maltId,yeastId,adjunctId;
			do{
				IngredientStep in = new IngredientStep();
				in.setQuantity(c.getDouble(1));
				in.setUnitType(c.getString(2));
				hopId=c.getInt(5);
				maltId=c.getInt(7);
				yeastId=c.getInt(6);
				adjunctId=c.getInt(4);
				
				if(hopId!=0)
					in.setIngredient(HopDAO.getHopById(db, hopId));
				else if(maltId!=0)
					in.setIngredient(MaltDAO.getMaltById(db, maltId));
				else if(yeastId!=0)
					in.setIngredient(YeastDAO.getYeastById(db, yeastId));
				else if(adjunctId!=0)
					in.setIngredient(AdjunctDAO.getAdjunctById(db, adjunctId));
				
				ins.add(in);
				
			}while(c.moveToNext());
		}
		return ins;
	}
	
	
	public static ArrayList<IngredientStep> getIngredientSteps(DatabaseHelper db)
	{
		ArrayList<IngredientStep> isList= new ArrayList<IngredientStep>();
		Cursor cursor =db.getReadableDatabase().rawQuery(INGREIDENTSTEP_SELECT_ALL, new String[]{});
		if(cursor.moveToFirst())	//if there are any entries in cursor
		{
			int hop_id,malt_id,yeast_id,adjunct_id;
			do
			{	IngredientStep is =new IngredientStep();
				is.setQuantity(cursor.getDouble(1));
				is.setUnitType(cursor.getString(2));
				adjunct_id=cursor.getInt(4);
				hop_id=cursor.getInt(5);
				yeast_id=cursor.getInt(6);
				malt_id=cursor.getInt(7);
				
				if(adjunct_id!=0)
					is.setIngredient(AdjunctDAO.getAdjunctById(db, adjunct_id));
				else if(hop_id!=0)
					is.setIngredient(HopDAO.getHopById(db, hop_id));
				else if(yeast_id!=0)
					is.setIngredient(YeastDAO.getYeastById(db,yeast_id));
				else if(malt_id!=0)
					is.setIngredient(MaltDAO.getMaltById(db,malt_id));
				
				isList.add(is);
			}
			//while there are more hops continue
			while(cursor.moveToNext());
		}
		return isList;
	}

	public static void deleteAll(DatabaseHelper db) {
		db.getWritableDatabase().delete(TABLE, null, null);
		
	}	
	/**
	 * 
	 * @param db
	 * @param recipe_id
	 * this deletes the ingredientSteps that belonged to a recipe that has just been deleted.  This is used to clean up the orphaned
	 * ingredientStep rows.
	 */
	public static void deleteRecipeSteps(DatabaseHelper db, int recipe_id)
	{
		db.getWritableDatabase().delete(TABLE, "recipe_id=?", new String[]{Integer.toString(recipe_id)});
	}
	
}
